﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using ELearning.BLL;
using ELearning.Common.CommonStr;
using ELearning.Common.Model;
using ELearning.Models;
using ELearning.Models.ViewModel;

namespace SiteAPI.Controllers.Common
{
    /// <summary>
    /// 字典相关控制器
    /// </summary>
    public class DictionaryController : BaseApiController
    {
        protected EDictionaryService EDictionaryService = new EDictionaryService();

        /// <summary>
        /// 根据code获取对应的字典列表
        /// </summary>
        private ServiceResponse<List<DictionaryViewModel>> GetDictionaryByPCode(string code)
        {
            var pdictionary = EDictionaryService.Find(w => w.TypeCode == code);
            var ls = EDictionaryService.FindList(m => !m.IsDelete).OrderBy(w => w.ParentID).OrderBy(w => w.Sort).ToList();
            var viewModels = new List<DictionaryViewModel>();
            GetSubViewModels(viewModels, ls, pdictionary.ID);
            return ServiceResponse<List<DictionaryViewModel>>.SuccessResponse(CommonConst.OprateSuccessStr, viewModels);
        }

        /// <summary>
        /// 构造层级菜单
        /// </summary>
        private void GetSubViewModels(List<DictionaryViewModel> viewModels, List<EDictionary> models, Guid parentId)
        {
            var subList = models.Where(m => m.ParentID == parentId).OrderBy(w => w.ParentID).OrderBy(w => w.Sort).ToList();
            foreach (var menu in subList)
            {
                var viewModel = new DictionaryViewModel
                {
                    id = menu.ID,
                    ParentID = menu.ParentID,
                    ParentName = models.FirstOrDefault(w => w.ID == menu.ParentID)?.TypeName ?? "",
                    TypeCode = menu.TypeCode,
                    TypeName = menu.TypeName,
                    Sort = menu.Sort
                };
                GetSubViewModels(viewModel.children, models, viewModel.id);
                if (!viewModel.children.Any())
                    viewModel.children = null;
                // viewModel.HasChildren = viewModel.Children==null?false: (viewModel.Children.Count > 0);
                viewModels.Add(viewModel);
            }
        }
        
        /// <summary>
        /// 获取分类列表
        /// </summary>
        [HttpGet, Route("api/Dictionary/GetCategoryList")]
        [AllowAnonymous]
        public ServiceResponse<List<DictionaryViewModel>> GetCategoryList()
        {
            var resp = GetDictionaryByPCode(DictionaryConst.CATEGORY_CODE);
            return resp;
        }

        /// <summary>
        /// 获取班级分类列表
        /// </summary>
        [HttpGet, Route("api/Dictionary/GetClassTypeList")]
        [AllowAnonymous]
        public ServiceResponse<List<DictionaryViewModel>> GetClassTypeList()
        {
            var resp = GetDictionaryByPCode(DictionaryConst.CLASS_TYPE_CODE);
            return resp;
        }
    }
}